//
//  String+Interpolation.swift
//  Yip
//
//  Created by bo wang on 2022/8/24.
//  Copyright © 2022 yip.com. All rights reserved.
//

import Foundation

extension String.StringInterpolation {
    /// 字符串插值生成不小于最低长度的字符串。
    /// 生成的字符串长度不足 minLength 位时，在前端补足 fill 指定的字符。
    /// - Parameters:
    ///   - value: 插入的值
    ///   - minLength: 字符串最小长度，忽略负值和0
    ///   - fill: 补位字符，默认为字符 0
    mutating func appendInterpolation(_ value: Any, minLength: Int, fill: Character = "0") {
        let len = max(0, minLength)
        let s = "\(value)"
        if s.count >= len {
            appendLiteral(s)
            return
        }
        appendLiteral(String(repeating: fill, count: len - s.count) + s)
    }
    
    /// 自定义字符串插值，为一个时间长度生成 HH:mm:ss格式的字符串
    /// - Parameter time: 时间长度
    mutating func appendInterpolation(HHmmss seconds: Int) {
        let s = seconds % 60
        let m = (seconds / 60) % 60
        let h = seconds / 3600
        let str = "\(h, minLength: 2):\(m, minLength: 2):\(s, minLength: 2)"
        appendLiteral(str)
    }
    
    /// 自定义字符串插值，为一个时间长度生成 mm:ss格式的字符串
    /// - Parameter time: 时间长度
    mutating func appendInterpolation(mmss seconds: Int) {
        let s = seconds % 60
        let m = (seconds / 60) % 60
        let str = "\(m, minLength: 2):\(s, minLength: 2)"
        appendLiteral(str)
    }
    
    /// 自定义字符串插值，为时间长度生成一个自动确定格式的字符串。
    /// 时长大于1小时格式为HH:mm:ss，否则格式为mm:ss。
    /// - Parameter seconds: 时间长度
    mutating func appendInterpolation(autoHHmmss seconds: Int) {
        if seconds / 3600 > 0 {
            appendInterpolation(HHmmss: seconds)
        } else {
            appendInterpolation(mmss: seconds)
        }
    }
}
